package httpTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Before;
import org.junit.Test;


public class HttpClientTest {
	
	private Map<String, String> params = new HashMap<String, String>();
	private String url = "http://127.0.0.1:8088/sms-frontal/MessageController/sendMsg";
	//private String url = "http://qf-coreuat-01:8148/sms-frontal/MessageController/sendMsg";
	
	@Before
	public void Init(){
		params.put("phoneNumber", "10000000000");
		params.put("deptType", "001");
		params.put("besType", "001");
		params.put("besId", "");
		params.put("content", "测试短信");
	}

	
	@Test
	public void testGet(){
		// 创建默认的httpClient实例.    
	    CloseableHttpClient httpclient = HttpClients.createDefault();  
	    // 创建httppost    
	    HttpGet httpGet = new HttpGet("http://www.baidu.com");
	    //HttpGet httpGet = new HttpGet("https://www.google.com/");
	    String result = null;
	    try {  
			HttpResponse response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "GBK");
			}
	    } catch (ClientProtocolException e) {  
	        e.printStackTrace();  
	    } catch (UnsupportedEncodingException e1) {  
	        e1.printStackTrace();  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    } finally {  
	        // 关闭连接,释放资源    
	        try {  
	            httpclient.close();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	    } 
	    System.out.println(result);
		
	}
	
	@Test
	public void testGetByHttp(){
		HttpURLConnection con = null;
		URL u = null;
		// 构建请求参数
		try {
			u = new URL("https://backend-server.com/hello");
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod("GET");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					con.getInputStream(), "UTF-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp.trim());
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		System.out.println(buffer);
	}
	
	
	
	@Test
	public void testHttpPost(){
		// 创建默认的httpClient实例.    
	    CloseableHttpClient httpclient = HttpClients.createDefault();  
	    // 创建httppost    
	    HttpPost httppost = new HttpPost(url);  
	    String result = null;
	    // 创建参数队列    
	    List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();  
	    formparams.add(new BasicNameValuePair("phoneNumber", params.get("phoneNumber")));  
	    formparams.add(new BasicNameValuePair("deptType", params.get("deptType")));  
	    formparams.add(new BasicNameValuePair("besType", params.get("besType")));  
	    formparams.add(new BasicNameValuePair("besId", params.get("besId")));  
	    formparams.add(new BasicNameValuePair("content", params.get("content")));  
	    UrlEncodedFormEntity uefEntity;  
	    try {  
	        uefEntity = new UrlEncodedFormEntity(formparams,  "UTF-8");  
	        httppost.setEntity(uefEntity);  
	        CloseableHttpResponse response = httpclient.execute(httppost);  
	        HttpEntity entity = response.getEntity();  
	        if (entity != null) {  
	            result = EntityUtils.toString(entity, "UTF-8");
	            }  
	    } catch (ClientProtocolException e) {  
	        e.printStackTrace();  
	    } catch (UnsupportedEncodingException e1) {  
	        e1.printStackTrace();  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    } finally {  
	        // 关闭连接,释放资源    
	        try {  
	            httpclient.close();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	    } 
	    System.out.println(result);
	}
	
	@Test
	public void testPostMethod(){
		HttpClient httpClient = new HttpClient();
		PostMethod method = new PostMethod(url);
		try {
			for (String key : params.keySet()) {
				method.setParameter(key, params.get(key));
			}
			method.releaseConnection();
			httpClient.executeMethod(method);
			String responses = method.getResponseBodyAsString();
			System.out.println(responses);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public  void testPost() throws Exception {
		HttpURLConnection con = null;
		URL u = null;
		// 构建请求参数
		StringBuffer sb = new StringBuffer();
		String data = "";
		if (params != null) {
			for (String e : params.keySet()) {
				sb.append(e);
				sb.append("=");
				sb.append(URLEncoder.encode(params.get(e),"UTF-8"));
				sb.append("&");
			}
			if (sb.length() > 0)
				data = sb.substring(0, sb.length() - 1);
		}
		try {
			u = new URL(url);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			OutputStreamWriter osw = new OutputStreamWriter(
					con.getOutputStream(), "UTF-8");
			osw.write(data);
			osw.flush();
			osw.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					con.getInputStream(), "UTF-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp.trim());
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		String responseResult = "";
		Pattern p = Pattern.compile("<div id=\"content\">(.*?)</div>");
	    Matcher m = p.matcher(buffer.toString());
	    while (m.find()) {
	        responseResult = m.group(1);
	    }
		String[] results = new String[2];
			if("OK".equals(responseResult)){
		    	results[0] = "0";
		    	results[1] = "短信发送成功";
		    }else{
		    	results[0] = buffer.toString();
		    	results[1] = buffer.toString();
		    }
			
		System.out.println(responseResult);
	}
		
	
}
